import getUserTempId from '@/utils/userTempId';
import { getUserInfo, userLogin, userLogout } from '@/api';

export default {
  namespaced: true,
  state: {
    userTempId: getUserTempId(),
    token: localStorage.getItem('token') || '',
    userinfo: {},
  },
  mutations: {
    SET_USER_TOKEN (state, payload) {
      state.token = payload;
      localStorage.setItem('token', payload);
    },
    SET_USER_INFO (state, payload) {
      state.userinfo = { ...payload };
    },
  },
  getters: {
    token (state) {
      return state.token;
    },
    userinfo (state) {
      return state.userinfo;
    },
  },
  actions: {
    // 登录
    async userLogin ({ commit, dispatch }, payload) {
      try {
        const { token } = await userLogin(payload);
        commit('SET_USER_TOKEN', token);
        dispatch('getUserInfo');
      } catch (err) {
        alert(err.message);
        return Promise.reject(err);
      }
    },
    // 注销
    async userLogout ({ commit }) {
      try {
        await userLogout();
        commit('SET_USER_TOKEN', '');
        commit('SET_USER_INFO', {});
      } catch (err) {
        alert(err.message);
      }

    },
    // 获取用户资料
    async getUserInfo ({ commit }) {
      try {
        const userinfo = await getUserInfo();
        commit('SET_USER_INFO', userinfo);
      } catch (err) {
        alert(err.message);
      }
    },
  },
};
